package com.jjc.android.activity

import android.os.Bundle
import android.text.InputFilter
import android.text.Spanned
import android.view.View
import android.widget.TextView
import com.allen.library.SuperButton
import com.hjq.toast.ToastUtils
import com.jjc.android.Constants
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.base.BaseActivity
import com.jjc.android.entity.*
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.Common
import com.jjc.android.util.paramEx
import com.jjc.android.view.onClick
import com.lzy.okgo.OkGo
import com.xw.repo.XEditText
import org.greenrobot.eventbus.EventBus
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern

class BindDeviceActivity : BaseActivity() {

    override val layoutId: Int = R.layout.activity_bind_device
    private val okBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.okBtn) }
    private val deviceEt: XEditText by lazy { findViewById<XEditText>(R.id.deviceEt) }
    private val scanBtn:View by lazy { findViewById(R.id.scanBtn) }
    private val errorTxt:TextView by lazy { findViewById(R.id.errorTxt) }


    private val pwdFilter: InputFilter = object : InputFilter {
        var pwdPattern: Pattern = Pattern.compile(
            "[^ -~]",
            Pattern.UNICODE_CASE or Pattern.CASE_INSENSITIVE
        )

        override fun filter(
            source: CharSequence?, start: Int, end: Int, dest: Spanned?,
            dstart: Int,
            dend: Int
        ): CharSequence? {
            val pwdMatcher: Matcher = pwdPattern.matcher(source)
            return if (pwdMatcher.find()) {
                ""
            } else null
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        setActivityTitle(getString(R.string.bind_device_txt))
        scanBtn.onClick{
            ScanActivity.start(this@BindDeviceActivity,Constants.ScanType.SCAN_DEVICE){
                deviceEt.setText(it)
            }
        }
        deviceEt.filters = arrayOf(pwdFilter)
        okBtn.onClick {
            val code = deviceEt.textEx
            if(code.isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_scan_sn_txt))
                return@onClick
            }
            showLoadingDialog()
            OkGo.post<LzyResponse<PageInfo<ScanDeviceDto>>>(Constants.getFormList)
                .paramEx(mutableMapOf(
                    "needpage" to 1,
                    "page" to 1,
                    "pagesize" to 1,
                    "formheaduuid" to "f5c3335196184797bb2c964d090e4165",
                    "filters" to listOf<KeyValuePair>(
                        KeyValuePair("ceb0lnznvqiuyvmb","9755f4f9-704e-4f29-854e-bb27e9ac167d"),
                        KeyValuePair("tfsqjqvs0sp7qvh4",code)
                    )
                ),true)
                .tag(deviceEt)
                .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<ScanDeviceDto>>>(false){
                    override fun onCallSuccess(response: LzyResponse<PageInfo<ScanDeviceDto>>) {
                        val scanDeviceDto = response.data?.first
                        if(scanDeviceDto==null){
                            ToastUtils.show(getString(R.string.no_find_device_txt))
                            hideLoadingDialog()
                        }else{
                            bindDevice(scanDeviceDto)
                        }
                    }

                    override fun onCallError(error: String?) {
                        super.onCallError(error)
                        hideLoadingDialog()
                    }
                })


        }
    }



    private fun bindDevice(device:ScanDeviceDto){
        OkGo.post<LzyResponse<PageInfo<DeviceDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf("page" to 1,"pagesize" to 1,"needpage" to 1,"formheaduuid" to "2582bc4c14914246807a26886f46dd0e","filters" to listOf<KeyValuePair>(
                KeyValuePair("ope0wk2ysioftswt",UserManager.userId()),
                KeyValuePair("bhmohipntdlpc61m",device.tfsqjqvs0sp7qvh4)
            )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<DeviceDto>>>(){
                override fun onCallSuccess(response: LzyResponse<PageInfo<DeviceDto>>) {
                    if(response.data?.data.isNullOrEmpty()){
                        OkGo.post<LzyResponse<Any>>(Constants.addFormRow)
                            .paramEx(mutableMapOf(
                                "formheaduuid" to "2582bc4c14914246807a26886f46dd0e",
                                "fields" to mapOf<String,Any?>(
                                    "1vbpshpsrd9ancnm" to device.xjgzqku0niynuevu.let { if(it.isNullOrEmpty()) null else it[0].url },
                                    "3m3fta753ew75mom" to device.va5o2bbxwgzu1cmb,
                                    "8vzt1b0ayishpetw" to device.id,
                                    "bhmohipntdlpc61m" to device.tfsqjqvs0sp7qvh4,
                                    "eozplztuhbbqpfon" to device.ceb0lnznvqiuyvmb,
                                    "hxpbdrvv39dczmmf" to device.jsonMember0ltcriv98n8wa1o8,
                                    "ikyjywsgjhhg2jmq" to Common.sdf.format(Date()),
                                    "jd6ugg6ktyckxbtp" to device.jsonMember9zd0k3hr1trcqesf,
                                    "lh00tcgkbbqpj185" to device.dvnobhxko5jl6y2c,
                                    "lktelicb0kqxm5jj" to UserManager.userInfo().tuoTuUserName,
                                    "ope0wk2ysioftswt" to UserManager.userInfo().tuoTuUserId,
                                    "xoroodxlsn4riasa" to UserManager.userInfo().tuoTuUserPhone
                                )
                            ),true)
                            .tag(this@BindDeviceActivity)
                            .execute(object : SimpleHttpCallback<LzyResponse<Any>>(){
                                override fun onCallSuccess(response: LzyResponse<Any>) {
                                    hideLoadingDialog()
                                    EventBus.getDefault().post(ChangeDeviceEvent())
                                    ToastUtils.show(getString(R.string.bind_success_txt))
                                    finish()
                                }

                                override fun onCallError(error: String?) {
                                    super.onCallError(error)
                                    hideLoadingDialog()
                                }

                            })
                    }else{
                        hideLoadingDialog()
                        ToastUtils.show(getString(R.string.device_added_txt))
                    }
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    hideLoadingDialog()
                }

            })
    }

}